//
//  MCOAuthViewController.swift
//  HXWeibo
//
//  Created by HX on 15/11/25.
//  Copyright © 2015年 HX. All rights reserved.
//

import UIKit
import SVProgressHUD

class MCOAuthViewController: UIViewController
{
    override func loadView()
    {
        //不用设置约束
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        // 这种方式要自己添加约束
//        self.view.addSubview(webView)
        
        // 加载授权界面
        let request = NSURLRequest(URL: MCNetworkTool.sharedInstance.oauthURL())
        
        webView.loadRequest(request)
        
        // 设置导航栏
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    func autoFill()
    {
        // 创建js代码
        let js = "document.getElementById('userId').value='15927990317'; document.getElementById('passwd').value='hx13972345508!'"
        //让webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    // 加载accessToken
    func loadAccessToken(code: String)
    {
        //发送网络请求
        MCNetworkTool.sharedInstance.loadAccessToken(code) { (result, error) -> () in
            
            if error != nil || result == nil
            {
                SVProgressHUD.showErrorWithStatus("网络不给力", maskType: SVProgressHUDMaskType.Black)
                
               dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                
                self.close()
               })
                return
            }
            
            //创建模型
            let userAccount = MCUserAccount(dict: result!)
            
            // 保存对象
            userAccount.saveAccount()
            
            print("userAccount: \(userAccount)")
            
            // 在切换界面之前把当前的界面销毁
            self.close()
            
            // 切换界面
            AppDelegate.switchRootViewController(false)
        }
    }
    
    deinit
    {
        print("---OAuthController销毁了---");
    }
    
    //关闭控制器
    func close()
    {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: 懒加载webView
    private lazy var webView = UIWebView()
}

// MARK: - 扩展 MCOAuthViewController  实现 UIWebViewDelegate协议
extension MCOAuthViewController: UIWebViewDelegate
{
    func webViewDidStartLoad(webView: UIWebView)
    {
        SVProgressHUD.showWithStatus("正在加载...", maskType:SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView)
    {
        SVProgressHUD.dismiss()
    }
    // webView加载链接 每当webView加载一个链接都会通过这个代理方法来询问我们这个地址是否可以加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        let urlStr = request.URL!.absoluteString
        print("urlStr -> \(urlStr)")
        
        // 如果没有点击同意或取消，直接加载
        if !urlStr.hasPrefix(MCNetworkTool.sharedInstance.redirect_uri)
        {
            return true
        }
        
        // 当用户点击同意或取消，拦截下来，不让它加载，我们来处理
        if let query = request.URL?.query
        {
//            print("query -> \(query)")
            let codeStr = "code="
            
            //如果请求是以 code= 开头的，那么就代表点击的是授权
            if query.hasPrefix(codeStr)
            {
                //先将query的类型转换为NSString, 点击授权，截取code的值
                let NSQuery = query as NSString
                let code = NSQuery.substringFromIndex(codeStr.characters.count)
                print("code -> \(code)")
                
                //加载accessToken
                loadAccessToken(code)
            }
            else
            {
                print("点击取消")
                self.close()
            }
        }
        
        return false
    }
}






























